<template>
  <div  style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>

      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
       :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="150" sortable show-header-overflow show-overflow :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="code" title="收款单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.code" placeholder="请输入收款单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="付款人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shipmentName" placeholder="请输入付款人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="amountCollected" title="收款金额" min-width="250" sortable />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input-number v-model="listQuery.amountCollectedLow"  controls-position="right"  :max="listQuery.amountCollectedUp" placeholder="下限"   />
            &nbsp;-&nbsp;
            <el-input-number  v-model="listQuery.amountCollectedUp" controls-position="right"  :min="listQuery.amountCollectedLow" placeholder="上限"  />
          </el-row>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="gmtBill" title="制单日期" min-width="400" sortable />
          <template v-slot:header="{ column }">
            <el-date-picker
              v-model="gmtBillRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              style="width:100%"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="value => changeDates(value, 'gmtBill')"
            />
          </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtCreated" title="创建时间" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtModified" title="修改时间" min-width="400" sortable />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="200">
        <template slot-scope="scope" >
          <el-tooltip class="item" effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <!-- <el-tooltip
            class="item"
            effect="dark"
            content="审核"
            placement="top"
            v-if="scope.row.status == '0'"
          >
            <vxe-button type="text" @click="funcCheck(scope.row.code)">
              <i class="el-icon-check" />
            </vxe-button>
          </el-tooltip> -->

          <el-tooltip class="item" effect="dark" content="修改" placement="top" v-if="scope.row.status == '0'">
            <vxe-button type="text" @click="funcEdit(scope.row.code, scope.row.type)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="scope.row.status == '0'">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete"/>
            </vxe-button>
          </el-tooltip>

        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <!-- <vxe-modal
      v-model="modelCheckFlag"
      title="审核"
      width="600"
      height="500"
      resize
    >
      <compCheck
        ref="checkRef"
        @fatherCheckMethod="fatherCheck"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal> -->

  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import compCheck from "./components/allocationCheck.vue";

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import { receiptList,receiptDelete} from "@/api/settlement";
import { getWarehouse} from '@/api/basicInfo'
import '@/assets/iconfont/iconfont.css';
import qs from 'qs'
export default {
  name: 'receiptList',
  components: {
    compCheck
  },
  data() {
    return {
      message: '',
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      statusList:[                       //状态
        { code: "0",name: "新建" },
        { code: "1", name: "待审核" },
        { code: "2",name: "审核通过" },
        { code: "3",name: "审核未通过" },
      ],
      warehouseData:[],
      loading: false,
      allAlign: 'center',
      tableData: [],
      gmtModifiedRange: '',
      gmtCreatedRange: '',
      gmtBillRange: '',
      modelAddFlag: false,
      modelbindingFlag:false,
      modelCheckFlag: false,

      modelEditFlag: false,
      modelDetailFlag: false,
      initFinishFlag: false,
      modelPrintFlag:false, //打印开关
      copy: false,
      issueList: [
        {code: '0', name:'否'},
        {code: '1', name:'是'},
      ],
      listQuery: {
        total: 0,             //总数
        createdName:'',         //创建人
        modifiedName:'',        //修改人
        gmtCreated:'',        //创建时间
        gmtModified:'',       //修改时间
        code:'',                                          //收货单号 ,
        customerCode:'',                                  //客户 ,
        gmtPlanArrival:'',                                //计划到货日期 ,
        putawayQuantity:'',                               //上架数量 ,
        receiveItemVOList:'',                             //明细 ,
        receivedQuantity:'',                              //收货数量 ,
        remarks:'',                                       //备注 ,
        shipmentName:'',                                  //入驻商 ,
        sourceCode:'',                                    //来源单号 ,
        status:'',                                        //状态 ,
        supplierCode:'',                                  //供应商 ,
        totalQuantity:'',                                 //订货数量 ,
        type:'',                                          //单据类型 ,
        warehouseCode:'',                                 //仓库
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
        totalQuantityStart: '',
        totalQuantityEnd: '',
        receivedQuantityStart: '',
        receivedQuantityEnd: '',
        putawayQuantityStart: '',
        putawayQuantityEnd: '',
        issue: '',
      },
    }
  },
  created() {
    this.findList();
    this.getWarehouse();
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  methods: {
    // 审核
    funcCheck(code) {
      this.$refs.checkRef.getInfo(code);
      this.modelCheckFlag = true;
    },
    // 审核组件的父方法
    fatherCheck() {
      this.modelCheckFlag = false;
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "check":
          this.modelCheckFlag = false;
          break;
        default:
      }
    },

      // 删除方法
      funcDelete(row) {
        this.$confirm('确认删除吗？').then(_ => {
          receiptDelete(row).then(response => {
            this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
            this.findList()
          })
        }).catch(_ => {
        })
      },

    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
      })
    },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    changeDates(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0];
        this.listQuery[`${prefix}End`] = value[1];
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    //作废
    funcBlank(code){
      this.$confirm('确认作废吗？').then(_ => {
        receiveBlank(code).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.findList()
        })
      })
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === '0') {
        return '新建'
      }

      if (cellValue === '1') {
        return '待审核'
      }
      if (cellValue === '2') {
        return '审核通过'
      }
      if (cellValue === '3') {
        return '审核未通过'
      }
    },
    formatterIssue({cellValue}){
      if(cellValue == '0'){
        return '否'
      }else if(cellValue == '1'){
        return  '是'
      }
      return cellValue
    },
    //获取列表
    findList() {
      this.loading = true
      return receiptList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.listQuery.total = response.data.total
        this.loading = false
      })
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 编辑
    funcEdit(code, type) {
        this.$router.push({
          path: "/settlement/editPayment",
          query: { code: code,}
        });

    },
    // 详情方法
    funcDetail(code) {
      this.$router.push({
        path: "/settlement/viewPayment",
        query: { code: code,}
      });
    },
    // 收货
    funcReceive(code) {
      this.$router.push({
        path: "/inbound/receiveCheckIn",
        query: { code: code,}
      });
    },
    // 单个下发
    funcCreateTask(code){
      let params = {
        taskType: 'RECEIVE',
        sourceCode: code
      }
      createTask(params).then((response)=>{
        this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
      }).then(()=>{
        this.findList();
      })

    },

    // 批量下发
    funcCreateBatchTask(){
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      if(selectRecords.length == 0){
        this.$message.error("请选择要下发的单据!");
        return
      }
      let codes = []
      selectRecords.forEach( i => {
        codes.push(i.code)
      })

      let params = {
        taskType: 'RECEIVE',
        sourceCodes: codes
      }

      createBatchTask(params).then((response)=>{
        this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
        this.findList()
      })
    },

    // 取消收货
    funcOnReceive(code) {
      this.$router.push({
        path: "/inbound/receiveCheckOut",
        query: { code: code,}
      });
    },

    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false
      this.findList()
    },
    //打印
    funcPrint() {
      let nowDate = new Date();
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1
      let date = nowDate.getDate()
      if (month >= 1 && month <= 9) {
        month = "0" + month
      }
      if (date >= 0 && date <= 9) {
        date = "0" + date
      }
      let systemDate = year + '-' + month + '-' + date;
      this.$refs.printRef.date = systemDate
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      let arr = []
      selectRecords.forEach( i => {
        arr.push(i.code)
      })
      this.$refs.printRef.getInfo(arr)
      this.modelPrintFlag = true
    },

    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 底部颜色设置
   /*  footerCellClassName({ $rowIndex, column, columnIndex }) {
      if (columnIndex === 0) {
        if ($rowIndex === 0) {
          return 'col-blue'
        } else {
          return 'col-red'
        }
      }
    }, */
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    }
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
}
</script>

<style>

.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
